<template>
	<view class="container">
		<view class="tab">
			<view
				class="tab_item"
				:class="{ active: current === index }"
				@click="tabsChange(item, index)"
				v-for="(item, index) in tabs"
				:key="index"
			>
				<text>{{ item.title }}</text>
			</view>
			<view class="block" :style="'left:' + (current ? '50%' : 0)"></view>
		</view>
		<swiper class="swiper-main" :current="current" @animationfinish="animationfinish">
			<swiper-item class="swiper-item">
				<view class="imgs">
					<view class="img" v-for="(img, idx) in imgs" :key="idx">
						<img :src="img.imgPath" mode="aspectFill" @click="topreviewImage(idx)" />
					</view>
					<!-- <view v-if="imgs.length == 0" style="text-align: center; width: 100%">暂无数据</view> -->
					<view v-if="imgs.length == 0" style="width: 100%; text-align: center; margin-top: 200rpx">
						<image
							style="width: 500rpx"
							mode="widthFix"
							src="https://zrws-1327345771.cos.ap-shanghai.myqcloud.com/images/1734702481602ONCKpkWwYg0g4d9d4ebe77ff36c5ee1a1590746db1fb.png"
						/>
					</view>
				</view>
			</swiper-item>
			<swiper-item class="swiper-item">
				<view class="imgs">
					<view class="img" v-for="(img, idx) in imgs" :key="idx">
						<video :src="img.imgPath" mode="aspectFill" />
					</view>
					<!-- <view v-if="imgs.length == 0" style="text-align: center; width: 100%">暂无数据</view> -->
					<view v-if="imgs.length == 0" style="width: 100%; text-align: center; margin-top: 200rpx">
						<image
							style="width: 500rpx"
							mode="widthFix"
							src="https://zrws-1327345771.cos.ap-shanghai.myqcloud.com/images/1734702481602ONCKpkWwYg0g4d9d4ebe77ff36c5ee1a1590746db1fb.png"
						/>
					</view>
				</view>
			</swiper-item>
		</swiper>

		<view class="btn_bottom" @click="uploadFunc" v-if="options.edit == '1'">
			<view class="icon_plus"> + </view>
			<view class="btn_text"> 上传更多我的研学风采 </view>
		</view>
	</view>
</template>

<script>
import indexApi from '@/api/yanxue/yanxue'
export default {
	data() {
		return {
			current: 0,
			options: {},
			tabs: [
				{
					title: '研学图片'
				},
				{
					title: '研学视频'
				}
			],
			imgs: []
		}
	},
	onLoad(op) {
		this.options = op
		this.getData()
	},
	methods: {
		topreviewImage(url) {
			let list = this.imgs.map(x => x.imgPath)
			uni.previewImage({
				current: url,
				urls: list
			})
		},
		// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
		// swiper滑动结束，分别设置tabs和swiper的状态
		animationfinish(e) {
			let current = e.detail.current
			this.current = current
		},
		uploadFunc() {
			if (this.current == 0) {
				this.upload()
			} else {
				this.uploadVideo()
			}
		},
		uploadVideo() {
			uni.chooseVideo({
				sourceType: ['album', 'camera'], // 设置视频来源，可选值为'album'（相册）和'camera'（相机），同时选择两者则允许从两者中选择
				maxDuration: 60, // 可选：设置可拍摄或选择的视频最长时长，单位为秒，默认60秒
				camera: 'back', // 可选：设置默认打开的相机，'back'为后置摄像头，'front'为前置摄像头，默认值为'back'
				success: res => {
					uni.showLoading({ title: '', mask: true })
					this.uploadImage(res.tempFilePath)
						.then(uploadResult => {
							// 在此处处理上传成功后的逻辑
							let obj = {
								albumId: this.options.id,
								imgPaths: uploadResult,
								type: 1
							}
							indexApi.imgSubmit(obj).then(res => {
								uni.showToast({ title: '上传成功', icon: 'none' })
								this.getData()
							})
						})
						.catch(error => {
							console.error('视频上传失败', error)
							// 在此处处理上传失败后的逻辑
						})
				},
				fail: function (err) {
					console.error('选择视频失败', err)
					// 在此处处理选择视频失败后的逻辑
				}
			})
		},
		upload() {
			uni.chooseImage({
				count: 9, // 设置最多选择9张图片
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'],
				success: chooseImageRes => {
					const uploadPromises = chooseImageRes.tempFilePaths.map(filePath => this.uploadImage(filePath))
					uni.showLoading({ title: '', mask: true })
					Promise.all(uploadPromises)
						.then(uploadResults => {
							uni.hideLoading()
							let obj = {
								albumId: this.options.id,
								imgPaths: uploadResults.join(','),
								type: 0
							}
							indexApi.imgSubmit(obj).then(res => {
								uni.showToast({ title: '上传成功', icon: 'none' })
								this.getData()
							})
						})
						.catch(error => {
							// 如果有任何一个上传请求失败了，这里会被调用
							console.error('图片上传失败', error)
						})
				},
				fail: err => {}
			})
		},
		uploadImage(filePath) {
			return new Promise((resolve, reject) => {
				// 这里应该是你的图片上传逻辑
				// 例如，使用uni.uploadFile将图片上传到服务器
				uni.uploadFile({
					url: 'https://yxapi.ziranweishi.com.cn/font/uploadByOss',
					filePath: filePath,
					name: 'file',
					success: uploadFileRes => {
						const res = JSON.parse(uploadFileRes.data)
						resolve(res.data)
					},
					fail: err => {
						reject(err)
					}
				})
			})
		},
		tabsChange(item, index) {
			this.current = index
			this.imgs = []
			this.getData()
		},
		getData() {
			indexApi.albumImgList({ albumId: this.options.id, page: 1, rows: 999, type: this.current }).then(res => {
				this.imgs = res.result.list
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	width: 100%;
	height: 631px;
	background: linear-gradient(0deg, #ffffff 0%, #c1f26c 100%);
	border-radius: 30px 30px 0px 0px;
	padding-top: 11px;
	.tab {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 173px;
		height: 33px;
		background: #ffffff;
		border-radius: 17px;
		margin: 0 auto;
		margin-bottom: 13px;
		position: relative;
		.tab_item {
			width: 50%;
			font-family: HarmonyOS Sans SC;
			font-weight: 400;
			font-size: 16px;
			color: #000000;
			text-align: center;
			z-index: 100;
		}
		.active {
			color: #fff;
			transition: all 0.3s ease;
		}
		.block {
			position: absolute;
			bottom: 0;
			width: 92px;
			height: 33px;
			background: #f95513;
			border-radius: 17px;
			z-index: 99;
			transition: all 0.3s ease;
		}
	}
	.swiper-main {
		min-height: 90vh;
	}
	.swiper-item {
		padding: 0 12px;
		box-sizing: border-box;
		.imgs {
			display: flex;
			flex-wrap: wrap;
			row-gap: 10px;
			column-gap: 14px;
			.img {
				width: 171.5px;
				height: 97.5px;
				img {
					width: 171.5px;
					height: 97.5px;
					object-fit: cover;
				}
				video {
					width: 171.5px;
					height: 97.5px;
					object-fit: cover;
				}
			}
		}
	}

	.btn_bottom {
		width: 231px;
		height: 33px;
		background: #f95513;
		border-radius: 17px;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		bottom: calc(env(safe-area-inset-bottom) + 36px);
		left: calc(50% - 115.5px);
		.icon_plus {
			width: 20px;
			height: 20px;
			border-radius: 20px;
			background-color: #fff;
			text-align: center;
			color: #f95513;
			font-size: 20px;
			font-weight: bold;
			line-height: 17.5px;
		}
		.btn_text {
			font-family: HarmonyOS Sans SC;
			font-weight: 500;
			font-size: 16px;
			color: #fff;
			margin-left: 10px;
		}
	}
}
</style>
